package org.kl.wx.service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.kl.wx.entity.App;
import org.kl.wx.entity.Groups;
import org.kl.wx.entity.WxUser;
import org.kl.wx.repository.GroupsDao;
import org.kl.wx.repository.WxUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Collections3;

import com.alibaba.fastjson.JSON;

@Component
@Transactional
public class WxUserService {
	private WxUserDao wxUserDao;

	// private AppService appService;
	@Autowired
	private AppService appService;

	@Autowired
	private GroupsDao groupsDao;

	public WxUser getWxUser(String guid) {
		return wxUserDao.findOne(guid);
	}

	public void saveWxUser(WxUser entity) {
		wxUserDao.save(entity);
	}

	public void deleteWxUser(String id) {
		wxUserDao.delete(id);
	}

	public List<WxUser> getByGroups(String groupsId) {
		return wxUserDao.findByGroupsId(groupsId);
	}

	public WxUser getByUnionid(String unionid) {
		List<WxUser> wxUser = wxUserDao.findByUnionid(unionid);
		if (Collections3.isEmpty(wxUser)) {
			return null;
		} else {
			return wxUser.get(0);
		}
	}

	public WxUser getByAppIdAndOpenid(String appId, String openid) {
		List<WxUser> userList = wxUserDao.findByAppIdAndOpenid(appId, openid);
		if (Collections3.isEmpty(userList)) {
			return null;
		} else {
			return userList.get(0);
		}
	}

	/**
	 * 删除多条记录
	 * 
	 * @param ids
	 */
	public String multiDelete(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0;
		for (String id : idArray) {
			if (StringUtils.isNotBlank(id)) {
				wxUserDao.delete(id);
				i++;
			}
		}
		return "删除" + i + "条记录";
	}

	/**
	 * 通用查改增删方法
	 * 
	 * @param effectRow
	 */
	public void crud(String inserted, String updated, String deleted) {
		// “新增”和“修改”时检查项目是否唯一
		List<WxUser> inserts = JSON.parseArray(inserted, WxUser.class);
		if (Collections3.isNotEmpty(inserts)) {
			for (WxUser a : inserts) {
				wxUserDao.save(a);

			}
		}
		List<WxUser> updates = JSON.parseArray(updated, WxUser.class);
		if (updates.size() > 0) {
			for (WxUser b : updates) {
				wxUserDao.save(b);
			}
		}
		List<WxUser> deletes = JSON.parseArray(deleted, WxUser.class);
		if (Collections3.isNotEmpty(deletes)) {
			wxUserDao.deleteInBatch(deletes);
		}
	}

	public void getWxUser(WxMpService wxMpService, WxMpUserList wxMpUserList, String appId) {
		try {
			// System.out.println(wxMpUserList.getOpenIds());
			List<String> userOpenIds = wxMpUserList.getOpenIds();
			String lang = "zh_CN"; // 语言
			App app = appService.getAppByOriginAppId(appId);
			if (app != null) {
				List<WxUser> old_wxuser = wxUserDao.findByAppId(appService.getAppByOriginAppId(appId).getId());
				if (Collections3.isNotEmpty(old_wxuser)) {
					for (WxUser user : old_wxuser) {
						user.setSubscribe(BasicConstants.NO_INT);
						user.setSubscribeTime(null);
						wxUserDao.save(user);
					}
				}
			}

			for (String id : userOpenIds) {
				WxMpUser user = wxMpService.userInfo(id, lang);
				Integer groupid = (int) wxMpService.userGetGroup(id);
				Groups group = new Groups();
				if (groupsDao.findByAppIdAndOriginGroupId(app.getId(), groupid) == null) {
					group.setApp(app);
					group.setOriginGroupId(groupid);
					group.setUserCount((int) wxMpService.groupGet().get(groupid).getCount());
					group.setGroupName(wxMpService.groupGet().get(groupid).getName());
					groupsDao.save(group);
				} else {
					group = groupsDao.findByAppIdAndOriginGroupId(app.getId(), groupid);
				}
				// List<WxMpGroup> groupList = wxMpService.groupGet();
				WxUser wxUser = new WxUser();
				if (wxUserDao.findByAppIdAndGroupsIdAndOpenid(app.getId(), group.getId(), user.getOpenId()) != null) {
					wxUser = wxUserDao.findByAppIdAndGroupsIdAndOpenid(app.getId(), group.getId(), user.getOpenId());
					wxUser.setSubscribe(BasicConstants.YES_INT);
					wxUser.setSubscribeTime(new Timestamp(user.getSubscribeTime()));

				} else {
					wxUser.setApp(app);
					wxUser.setCity(user.getCity());
					wxUser.setCountry(user.getCountry());
					wxUser.setGroups(group);
					wxUser.setHeadimgurl(user.getHeadImgUrl());
					wxUser.setLanguage(user.getLanguage());
					wxUser.setNickname(user.getNickname());
					wxUser.setProvince(user.getProvince());
					wxUser.setSubscribe(BasicConstants.YES_INT);
					wxUser.setSubscribeTime(new Timestamp(user.getSubscribeTime() * 1000));
					int i = 0;
					if (StringUtils.equals(user.getSex(), "男")) {
						i = 1;
					} else if (StringUtils.equals(user.getSex(), "女")) {
						i = 2;
					}
					wxUser.setUserSex(i);
					wxUser.setUnionid(user.getUnionId());
					wxUser.setOriginGroupId(groupid);
					wxUser.setOpenid(user.getOpenId());
				}
				wxUserDao.save(wxUser);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public List<WxUser> getAllWxUser() {
		return wxUserDao.findAll();
	}

	/**
	 * 按条件查询
	 */
	public List<WxUser> getAllWxUser(Map<String, Object> searchParams, String sortType, String orderType) {
		Specification<WxUser> spec = KLDynamicSpecifications.buildSpecification(searchParams, WxUser.class);
		return wxUserDao.findAll(spec, CRUDUtils.buildSort(sortType, orderType));
	}

	/**
	 * 按条件查询
	 */
	public List<WxUser> getWxUser(Map<String, Object> searchParams) {
		Specification<WxUser> spec = buildSpecification(searchParams);
		List<WxUser> result = wxUserDao.findAll(spec);
		return result;
	}

	/**
	 * 按条件分页查询
	 */
	public Page<WxUser> getWxUser(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<WxUser> spec = buildSpecification(searchParams);

		return wxUserDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<WxUser> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<WxUser> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), WxUser.class);
		return spec;
	}

	@Autowired
	public void setWxUserDao(WxUserDao wxUserDao) {
		this.wxUserDao = wxUserDao;
	}

}